package cn.highedu.coolsharkhub.filter;

import cn.highedu.coolsharkhub.pojo.vo.UserVO;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * 访问过滤器
 * 用于拦截未登录的用户访问后台资源
 * 如果未登录，则重定向到登录页面
 * 如果已登录，则放行
 * @author HighEDU
 */
@WebFilter(filterName = "accessFilter", urlPatterns = {"/admin.html", "/api/*"})
public class SecurityFilter implements Filter {
    private final Logger logger = LoggerFactory.getLogger(SecurityFilter.class);
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        logger.info("SecurityFilter init");
    }

    @Override
    public void doFilter(ServletRequest request,
                         ServletResponse response,
                         FilterChain chain)
            throws IOException, ServletException {
        logger.info("SecurityFilter doFilter");
        //类型转换
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        //得到会话对象
        HttpSession session = req.getSession();
        //得到登录成功时保存的用户对象
        UserVO user = (UserVO) session.getAttribute("user");
        //如果用户对象不为空，则放行
        if (user != null) {
            //放行
            chain.doFilter(request, response);
            logger.info("放行");
        } else {
            //重定向到登录页面
            resp.sendRedirect("/login.html");
            logger.info("重定向到登录页面");
        }
    }

    @Override
    public void destroy() {
        logger.info("SecurityFilter destroy");
    }
}
